//
//  VRLoginViewController.m
//  VRContact
//
//  Created by veer on 2017/4/6.
//  Copyright © 2017年 veer. All rights reserved.
//111

#import "VRLoginViewController.h"
#import "VRMainViewController.h"
#import <AddressBook/AddressBook.h>

#import "UIImage+VR.h"


@interface VRLoginViewController()

/** 钮 */
@property (nonatomic, weak) UITextField *usernameTf;

/** 用户名 */
@property (nonatomic, copy) NSString *username;

/** 登录次数 */
@property (nonatomic, assign) NSInteger loginCount;

@end


@implementation VRLoginViewController


- (void)viewDidLoad {
    
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.view.backgroundColor = [UIColor whiteColor];
    self.title = @"登录";
    
    [self setupSubView];
}


- (void)setupSubView
{
    
    // 背景图
    UIImageView *bgImgView = [[UIImageView alloc] init];
    bgImgView.contentMode = UIViewContentModeScaleAspectFill;
    bgImgView.image = [UIImage imageNamed:@"mian_bg"];
    [self.view addSubview:bgImgView];
    [bgImgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.mas_equalTo(self.view);
        //        make.height.mas_equalTo(520 * VRScreenScale);
        make.bottom.mas_equalTo(self.view);
    }];
    
    
//    UIView *maskView = [[UIView alloc] init];
//    maskView.backgroundColor = VRColorAlpha(0, 0, 0, 0.4);
//    [self.view addSubview:maskView];
//    [maskView mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.edges.mas_equalTo(self.view);
//    }];
    
    UIView *loginView = [[UIView alloc] init];
    loginView.backgroundColor = [UIColor whiteColor];
    loginView.layer.masksToBounds = YES;
    loginView.layer.cornerRadius = 5;
    [self.view addSubview:loginView];
    [loginView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(20);
        make.right.mas_equalTo(-20);
        make.centerY.mas_equalTo(self.view).offset(-100);
        make.height.mas_equalTo(200);
    }];
    
    UILabel *titleLbl = [[UILabel alloc] init];
//    titleLbl.text = @"登陆";
    titleLbl.textAlignment = NSTextAlignmentCenter;
    titleLbl.textColor = VRColor(100, 100, 100);
    titleLbl.font = VRFont(16);
    [loginView addSubview:titleLbl];
    [titleLbl mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_equalTo(0);
        make.top.mas_equalTo(0);
        make.height.mas_equalTo(40);
    }];
    
    UITextField *usernameTf = [[UITextField alloc] init];
    usernameTf.placeholder = @"请输入用户名";
    usernameTf.returnKeyType = UIReturnKeyGo;
    usernameTf.font = VRFont(15);
    usernameTf.layer.borderColor = VRColor(0xbb, 0xbb, 0xbb).CGColor;
    usernameTf.layer.borderWidth = 0.5;
    usernameTf.layer.masksToBounds = YES;
    usernameTf.layer.cornerRadius = 5;
    usernameTf.leftView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 10, 0)];
    usernameTf.leftViewMode = UITextFieldViewModeAlways;
    usernameTf.delegate = self;
    [loginView addSubview:usernameTf];
    self.usernameTf = usernameTf;
    [usernameTf mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(titleLbl.mas_bottom).offset(15);
        make.left.mas_equalTo(20);
        make.right.mas_equalTo(-20);
        make.height.mas_equalTo(35);
    }];
    
    UIButton *loginBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [loginBtn setTitle:@"登陆" forState:UIControlStateNormal];
    loginBtn.titleLabel.font = VRFont(16);
    [loginBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [loginBtn setBackgroundImage:[UIImage imageWithColor:VRColor(240, 240, 240)] forState:UIControlStateHighlighted];
    [loginBtn setBackgroundImage:[UIImage imageNamed:@"register_button_normal"] forState:UIControlStateNormal];
    [loginBtn addTarget:self action:@selector(onLoginBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [loginView addSubview:loginBtn];
    [loginBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(20);
        make.right.mas_equalTo(-20);
        make.bottom.mas_equalTo(-20);
        make.height.mas_equalTo(40);
    }];
    
//    UIView *lineView = [[UIView alloc] init];
//    lineView.backgroundColor = VRColor(0xbb, 0xbb, 0xbb);
//    [loginView addSubview:lineView];
//    [lineView mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.bottom.mas_equalTo(loginBtn.mas_top);
//        make.left.right.mas_equalTo(0);
//        make.height.mas_equalTo(0.5);
//    }];
    
    [usernameTf becomeFirstResponder];
    
    NSUserDefaults *userdef = [NSUserDefaults  standardUserDefaults];
    NSString *userName = [userdef valueForKey:@"username"];
    if (userName) {
        
        usernameTf.text = userName;
    }
    
    // 判断是否授权
    ABAuthorizationStatus authorizationStatus = ABAddressBookGetAuthorizationStatus();
    if (authorizationStatus == kABAuthorizationStatusNotDetermined) {
        // 请求授权
        ABAddressBookRef addressBookRef = ABAddressBookCreate();
        ABAddressBookRequestAccessWithCompletion(addressBookRef, ^(bool granted, CFErrorRef error) {
            if (granted) { // 授权成功
                
                NSLog(@"授权成功！");
            } else {  // 授权失败
                
            }
        });
    }
}



#pragma mark - net
/** login */
- (void)loginWith:(NSString *)userName
{
    
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    param[@"card"] = userName;
    
    AFHTTPSessionManager *sessionMgr = [AFHTTPSessionManager manager];
//    sessionMgr.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html", nil];
    
//    sessionMgr.responseSerializer.acceptableContentTypes = [[NSSet  alloc] initWithObjects:@"application/json", nil];

    
    AFJSONResponseSerializer *json =[AFJSONResponseSerializer serializer];
    json.removesKeysWithNullValues = YES;
    sessionMgr.responseSerializer = json;
    
    sessionMgr.requestSerializer = [AFHTTPRequestSerializer serializer];
    
    
    // 设置超时时长
    [sessionMgr.requestSerializer willChangeValueForKey:@"timeoutInterval"];
    sessionMgr.requestSerializer.timeoutInterval = 10.0;
    [sessionMgr.requestSerializer didChangeValueForKey:@"timeoutInterval"];
    
    [sessionMgr POST:@"" parameters:param progress:^(NSProgress * _Nonnull uploadProgress) {
        
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        // 返回：struts=0 登录成功   struts=1  账号有误请重新登录
        VRLog(@"responseObject:%@", responseObject);
        NSInteger struts = [responseObject[@"struts"] integerValue];
        
        if (struts == 0) {
            
            [SVProgressHUD showSuccessWithStatus:@"登陆成功"];
            self.username = self.usernameTf.text;

            VRMainViewController *mainVc = [[VRMainViewController alloc] init];
            mainVc.username = self.usernameTf.text;
            [mainVc.navigationController setNavigationBarHidden:YES animated:NO];
            [self.navigationController pushViewController:mainVc animated:YES];
            
            // 存账号密码
            NSUserDefaults *userdef = [NSUserDefaults  standardUserDefaults];
            [userdef setValue:userName forKey:@"username"];
            [userdef synchronize];
            
            NSHTTPCookieStorage *cookieJar = [NSHTTPCookieStorage sharedHTTPCookieStorage];
            for (int i = 0;  i < cookieJar.cookies.count; i ++) {
                
                NSHTTPCookie *cookie = [cookieJar cookies][i];
                if (i == cookieJar.cookies.count - 1) {
                    
                    [userdef setValue:cookie.value forKey:VRLoginCookieKey];
                    
                    NSData *cookiesData = [NSKeyedArchiver archivedDataWithRootObject:@[cookie]];
                    [userdef setObject:cookiesData forKey:@"doctorcookiesKey"];
                    
                    [userdef synchronize];
                }
            }
            
        }else if (struts == 1){
            
            [SVProgressHUD showErrorWithStatus:@"账号有误请重新登录"];
            [self.usernameTf becomeFirstResponder];
            
            // 登录失败就重新登录一次（接口有bug）
            if (self.loginCount < 1) {
                
                self.loginCount++;
                [self loginWith:userName];
            }
        }else{
            
            [SVProgressHUD showErrorWithStatus:@"未知错误"];
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        VRLog(@"error:%@", error);
        
        if (error.code == -1009) {  // 网络连接错误
            
            [SVProgressHUD showErrorWithStatus:@"网络连接错误"];
        }else if (error.code == -1001){ // 链接超时
            
            [SVProgressHUD showErrorWithStatus:@"请求超时"];
        }else{
            
            [SVProgressHUD showErrorWithStatus:@"请求错误"];
        }
    }];
    
}



#pragma mark - action
- (void)onLoginBtnClick:(UIButton *)sender
{
    
    [self.view endEditing:YES];
    
    NSString *userName = self.usernameTf.text;
    if (userName.length == 0) {
        [SVProgressHUD showErrorWithStatus:@"请输入用户名"];
        [self.usernameTf becomeFirstResponder];
        return;
    }
    
    [self loginWith:userName];
}



@end
